const Mock = require('mockjs');

// 地理分布配置
const GEO_CONFIG = {
  chinaBounds: { // 中国主要坐标范围
    lng: [105.0, 123.0],
    lat: [20.0, 40.0]
  },
  majorCities: { // 主要城市群坐标范围
    lng: [116.0, 120.0], // 京津冀/长三角
    lat: [28.0, 34.0]    // 珠三角/长江中游
  }
};

// 生成单店数据
const generateStore = () => {
  const fullCity = Mock.Random.city(true);
  const [province, city] = fullCity.split(' ');
  const isMajorCity = Mock.Random.boolean(0.8);

  return {
    basicInfo: Mock.mock({
      storeId: Mock.Random.id().slice(0, 9), // 9位唯一ID
      storeName: `${province}${city}${Mock.Random.cword('分东南西北一二三四五')}店`,
      province: province,
      city: city,
      coordinates: generateCoordinates(isMajorCity),
      storeType: ['直营', '加盟'][Mock.Random.integer(0, 1)],
      areaSize: Mock.Random.integer(80, 300),
      openingDate: generateOpeningDate(),
      tags: [getAreaType()]
    }),
    dailyData: generateDailyData(),
    monthlyData: generateMonthlyData(),
    annualData: generateAnnualData()
  };
};


// 生成开业日期
const generateOpeningDate = () => {
  // 定义时间范围
  const startDate = new Date('2015-01-01').getTime();
  const endDate = new Date('2023-12-31').getTime();
  // 生成随机时间戳
  const randomTimestamp = Mock.Random.integer(startDate, endDate);
  // 格式化为日期字符串
  return new Date(randomTimestamp).toISOString().split('T')[0];
};

// 生成地理坐标
const generateCoordinates = (isMajorCity) => ({
  lng: Mock.Random.float(
    isMajorCity ? GEO_CONFIG.majorCities.lng[0] : GEO_CONFIG.chinaBounds.lng[0],
    isMajorCity ? GEO_CONFIG.majorCities.lng[1] : GEO_CONFIG.chinaBounds.lng[1]
  ).toFixed(5),
  lat: Mock.Random.float(
    isMajorCity ? GEO_CONFIG.majorCities.lat[0] : GEO_CONFIG.chinaBounds.lat[0],
    isMajorCity ? GEO_CONFIG.majorCities.lat[1] : GEO_CONFIG.chinaBounds.lat[1]
  ).toFixed(5)
});

// 区域类型生成
const getAreaType = () =>
  ['商业区', '社区', '学校', '景区', '交通枢纽'][Mock.Random.integer(0, 4)];


// 生成每日数据
const generateDailyData = () => {
  const baseSales = Mock.Random.integer(30000, 80000);
  const startDate = new Date('2024-01-01');

  return Array.from({ length: 366 }, (_, index) => {
    // 生成连续日期
    const currentDate = new Date(startDate);
    currentDate.setDate(startDate.getDate() + index);

    // 格式化日期为YYYY-MM-DD
    const year = currentDate.getFullYear();
    const month = String(currentDate.getMonth() + 1).padStart(2, '0');
    const day = String(currentDate.getDate()).padStart(2, '0');

    return {
      date: `${year}-${month}-${day}`,
      revenue: {
        amount: Mock.Random.integer(baseSales * 0.9, baseSales * 1.1),
        yoy: `${Mock.Random.float(-5, 15).toFixed(1)}%`,
        mom: `${Mock.Random.float(-8, 10).toFixed(1)}%`,
        target: baseSales
      },
      profit: Mock.Random.integer(8000, 35000),
      orderCount: Mock.Random.integer(150, 600),
      customerFlow: Mock.Random.integer(200, 800)
    };
  });
};


// 生成月度数据
export const generateMonthlyData = () =>
  Array.from({ length: 12 }, (_, month) => ({
    month: month + 1,
    costs: {
      total: Mock.Random.integer(200000, 800000),
      ingredients: Mock.Random.integer(80000, 300000),
      labor: Mock.Random.integer(50000, 200000),
      operation: Mock.Random.integer(30000, 150000),
      energy: Mock.Random.integer(10000, 50000),
      maintenance: Mock.Random.integer(5000, 30000),
      financial: Mock.Random.integer(10000, 80000)
    },
    membership: {
      consumptionRatio: `${Mock.Random.float(20, 60).toFixed(1)}%`,
      newMembers: Mock.Random.integer(50, 300),
      repurchaseRate: `${Mock.Random.float(15, 45).toFixed(1)}%`
    },
    deliveryRatio: `${Mock.Random.float(15, 55).toFixed(1)}%`,
    staffEfficiency: Mock.Random.float(500, 2000).toFixed(0),
    areaEfficiency: Mock.Random.float(50, 200).toFixed(1),
    tableTurnover: Mock.Random.float(1.5, 4.5).toFixed(1),
    staffCount: Mock.Random.integer(8, 20)
  }));


// 生成年度数据
export const generateAnnualData = () => ({
  promotions: {
    springFestival: generateHolidayData(),
    laborDay: generateHolidayData(),
    nationalDay: generateHolidayData(),
    summer: generateHolidayData()
  },
  avgCustomerValue: Mock.Random.integer(35, 85),
  rating: generateRating(),
  reviews: {
    positive: Mock.Random.integer(500, 2000),
    negative: Mock.Random.integer(0, 50)
  },
  yearGrowth: `${Mock.Random.float(4, 9).toFixed(1)}%`
});

function generateRating() {
  const rawValue = Mock.Random.float(3.5, 5.0);
  // 处理浮点精度 + 四舍五入
  const rating = Math.min(5.0, parseFloat(rawValue.toFixed(1)));
  return rating;
}

// 生成节假日通用数据
const generateHolidayData = () => ({
  revenue: Mock.Random.integer(100000, 250000),
  profit: Mock.Random.integer(30000, 100000),
  orderCount: Mock.Random.integer(800, 2000),
  customerFlow: Mock.Random.integer(1000, 3000),
  revenueGrowth: `${Mock.Random.float(10, 50).toFixed(1)}%`,
  roi: Mock.Random.float(1, 5).toFixed(2),
  newCustomerRatio: `${Mock.Random.float(15, 40).toFixed(1)}%`
});

// 批量生成并保存
const generateStores = (count = 20) => {
  console.time('Data generation completed');
  const stores = Array.from({ length: count }, (_, i) => {
    if ((i + 1) % 100 === 0) console.log(`Generated ${i + 1} records`);
    return generateStore();
  });
  console.timeEnd('Data generation completed');
  return stores;
};

// 保存到文件
const fs = require('fs');
fs.writeFileSync('stores.json',
  JSON.stringify(generateStores(), null, 2));
console.log('Data saved to stores.json');